-
Notifications
You must be signed in to change notification settings - Fork 3
/
linked_stack.py
41 lines (33 loc) · 1.04 KB
/
linked_stack.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Node:
def __init__(self, value, bottom_node: 'Node'=None):
self.value = value
self.__bottom_node = bottom_node
@property
def bottom_node(self):
return self.__bottom_node
@bottom_node.setter
def bottom_node(self, node):
self.__bottom_node = node
class LinkedStack:
def __init__(self):
self.first_node = None
self.count = 0
def __iter__(self):
node = self.first_node
while node:
yield node.value
node = node.bottom_node
def push(self, element):
if self.count == 0:
self.first_node = Node(value=element, bottom_node=None)
else:
new_node = Node(value=element, bottom_node=self.first_node)
self.first_node = new_node
self.count += 1
def pop(self):
if self.count == 0:
raise Exception('Stack is empty!')
node_value = self.first_node.value
self.first_node = self.first_node.bottom_node
self.count -= 1
return node_value